package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shopkeeper.entity.activity.ActivityHomeAd;
import cn.hiapi.shopkeeper.entity.activity.ActivityLotteryItem;
import cn.hiapi.shopkeeper.jpa.activity.ActivityHomeAdJpa;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2023/2/5 0:15
 */
@Service
public class ActivityHomeAdService extends AbsBasicService<ActivityHomeAdJpa, ActivityHomeAd, Long> {
    private final DispatchContext dispatchContext;

    public ActivityHomeAdService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }

    /**
     * 广告活动开始
     *
     * @param list
     */
    @Transactional
    public void activityStart(List<ActivityHomeAd> list) {
        for (ActivityHomeAd ad : list) {
            ad.setStatus(1);
            ad.setUpdated(System.currentTimeMillis());

            List<ActivityLotteryItem> items = this.dispatchContext.getServiceOne(ActivityLotteryItemService.class).findByAid(ad.getId());
            List<Long> collect = items.stream().filter(e -> e.getType() == 0 && e.getLid() > 0).map(ActivityLotteryItem::getLid).collect(Collectors.toList());
            this.dispatchContext.getServiceOne(ActivityLotteryAdService.class).start(collect);
            this.save(ad);
        }
    }

    /**
     * 广告活动结束
     *
     * @param list
     */
    @Transactional
    public void activityEnd(List<ActivityHomeAd> list) {
        for (ActivityHomeAd ad : list) {
            ad.setStatus(2);
            ad.setUpdated(System.currentTimeMillis());
            List<ActivityLotteryItem> items = this.dispatchContext.getServiceOne(ActivityLotteryItemService.class).findByAid(ad.getId());
            List<Long> collect = items.stream().filter(e -> e.getType() == 0 && e.getLid() > 0).map(ActivityLotteryItem::getLid).collect(Collectors.toList());
            this.dispatchContext.getServiceOne(ActivityLotteryAdService.class).end(collect);
            this.save(ad);
        }
    }
}
